package com.my.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 下载文件功能
* <dl>
* <dt>作用:</dt>
* <dd>1.向远程服务器下载文件</dd>
* <dd>2.向本地服务器下载文件</dd>
* </dl>
 * @author zc
 *
 */
public class DownloadFileUtil {
	private static final Logger logger = LoggerFactory.getLogger(DownloadFileUtil.class);

	public static void main(String[] args) throws Exception {
		remoteDownload(
				"http://wx.qlogo.cn/mmopen/ajNVdqHZLLD2scoAFT2iasibONREVab8XONvpzkggOcuPYDEogPp7dUp4mib3N2P5d44sxBZrTpMy9wt8DkZjqibDw/0",
				"51bi.jpg", "c:\\image\\");
	}

	/**
	 *  
	 * @param urlString 网址
	 * @param filename 下载之后的文件名字
	 * @param savePath 文件保存的路劲
	 * @return 是否保存成功
	 * @throws Exception
	 */
	public static boolean remoteDownload(String urlString, String filename,
			String savePath) throws Exception {
		try {
			// 构造URL
			URL url = new URL(urlString);
			// 打开连接
			URLConnection con = url.openConnection();
			// 设置请求超时为5s
			con.setConnectTimeout(5 * 1000);
			// 输入流
			InputStream is = con.getInputStream();

			// 1K的数据缓冲
			byte[] bs = new byte[1024];
			// 读取到的数据长度
			int len;
			// 输出的文件流
			File sf = new File(savePath);
			if (!sf.exists()) {
				sf.mkdirs();
			}
			OutputStream os = new FileOutputStream(sf.getPath() + "\\"
					+ filename);
			// 开始读取
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			// 完毕，关闭所有链接
			os.close();
			is.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}
	
	
	
	/**
	 * 客户向本地服务器下载文件
	 * @param request 
	 * @param response
	 * @param storeName
	 * @param contentType
	 * @param realName
	 * @throws Exception
	 */
	public static void localDownload(HttpServletRequest request, HttpServletResponse response, String storeName,
			String contentType, String realName, String downloadpath) throws Exception {
		String ctxPath = downloadpath;
		String downLoadPath = ctxPath + storeName;
		long fileLength = new File(downLoadPath).length();
		request.setCharacterEncoding("UTF-8");
		response.setContentType(contentType + ";charset=UTF-8");
		response.setHeader("Content-disposition", "attachment; filename="
				+ new String(realName.getBytes("utf-8"), "ISO-8859-1"));
		response.setHeader("Content-Length", String.valueOf(fileLength));
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		bis = new BufferedInputStream(new FileInputStream(downLoadPath));
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[(int) fileLength];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.flush();
		bos.close();
	}
}
